import { Injectable } from '@angular/core';
import { environment } from '../../../environments/environment';

import { StorageService } from './storage.service';
import { Profile } from '../../framework/login/models/profile.model';
import { GoogleAnalyticsBeacon } from '../models/googleAnalytics.model';
import { GoogleAnalyticsService } from '../../../../node_modules/googleanalytics-angular/src';

/**
 * TODO: preload service confguration on user login.
 */
@Injectable()
export class AnalyticsService {    
    constructor(private googleAnalyticsService: GoogleAnalyticsService) { }

    public config(){        
        let profile: Profile = StorageService.get().userInfo;
        var trackingId = environment.gaTrackingId;
        var options = {
            clientId: profile.userId,
            cookieDomain: 'auto',
            name: 'globalAccess', 
            namedTracker: environment.production
        }                
        
        //on multiple relogs, avoid triggering multiple instances
        this.googleAnalyticsService.event.observers = [];
        this.googleAnalyticsService.pageview.observers = [];

        this.googleAnalyticsService.configure(trackingId, options);
        this.googleAnalyticsService.set({"dimension1": profile.userId});
    }

    public sendBeacon(beacon: GoogleAnalyticsBeacon) {
        let profile: Profile = StorageService.get().userInfo;
        beacon.label.Date = new Date();
        beacon.label.AccountId = profile.accountId;
        beacon.label.UserId = profile.userId;
        
        this.googleAnalyticsService.event.emit({
            category: beacon.category,
            action: beacon.action,
            label: JSON.stringify(beacon.label)
        });    
    }  
    
    public close(){
        this.googleAnalyticsService.close();
    }
}